import * as React from 'react';
import { CSSProperties } from 'react';
import { Button, Tooltip } from 'antd';
import { DownloadOutlined } from '@ant-design/icons/lib';

interface DownloadProps {
  url?: string;
  fileName?: string;
  contents?: string | Uint8Array;

  className?: string;
  style?: CSSProperties;
}

const DownLoad: React.FC<DownloadProps> = (props) => {
  const { url, fileName, contents, className, style } = props;
  if (url || contents) {
    let downloadUrl: string;
    if (contents) {
      const blob = new Blob([contents], { type: 'application/octet-stream' });
      downloadUrl = URL.createObjectURL(blob);
    } else {
      downloadUrl = url;
    }

    return (
      <Tooltip title={'下载文件到本地'}>
        <Button
          size={'small'}
          icon={<DownloadOutlined />}
          type={'dashed'}
          href={downloadUrl}
          download={fileName}
          shape={'round'}
          className={className}
          style={style}>
          下载
        </Button>
      </Tooltip>
    );
  }

  return null;
};

DownLoad.defaultProps = {
  fileName: '',
};

export default DownLoad;
